var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const bodyParser=require('body-parser');
const session = require('express-session');

var indexRouter = require('./routes/index.controller');
var usersRouter = require('./routes/users.controller');
var AdminRouter = require('./routes/admin.controller');
var MessageRouter = require('./routes/message.controller');

var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
app.use('public',express.static('public',{'maxAge':36000000}));
app.use(session({
  secret:'secret',
  resave:true,
  saveUninitialized:false,
  cookie:{
    maxAge:1000*60*30,
  }
}))

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// catch 404 and forward to error handler
let print=function(req, res, next) {
  console.log('请求路径'+req.path);
  if(req.method === "GET"){
    console.log('请求数据：'+JSON.stringify(req.query));
  }
  else{
    console.log('请求数据：'+JSON.stringify(req.body));
  }
  console.log('请求类型：'+req.method);
  console.log('当前时间：'+new Date());
  console.log('-----分割线-----');
  next();
}
app.use(print);
app.use('/', indexRouter);
app.use('/user', usersRouter);
app.use('/admin', AdminRouter);
app.use('/message', MessageRouter);



// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});
const socket = require('./util/socket.js');
var debug = require('debug')('chat:server');
var http = require('http');

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port,function (){
  console.log('listening on *:'+port);
});

socket.getSocket(server);
/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}